/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package url;

import util.CleverBrowser;
import java.net.MalformedURLException;

/**
 *
 * @author kuksenok
 */
public class CleverURL extends SimpleURL{

    CleverBrowser browser;
    long interval;
    int methodID;

    boolean updated = false;
    long length = 0;

    /**
     *
     * @param URL
     * @param cb
     * @param interval
     * @param methodID
     * @throws MalformedURLException
     */
    public CleverURL(String URL, CleverBrowser cb, long interval, int methodID, boolean verbose) throws MalformedURLException{
        super(URL, verbose);
        this.interval  = interval;
        this.methodID = methodID;
        browser = cb;
    }

    /**
     * Given the interval specified at construction, checks if a page has been updated
     * at least that long ago; if so, retrieves that text; otherwise, re-downloads, and saves ot the database.
     *
     * @return full page content, OR null if anything's gone wrong with the database
     */
    @Override
    public StringBuilder getContents() {
        if(isLostCause()){
            return null;
        }
        String URL = super.getAddress();
        StringBuilder sb;
        if(!browser.beenUpdatedWithin(URL, methodID, interval)){
            sb = super.getContents();
            if(browser.addContent(URL, sb, methodID)){
                //System.out.println(URL+" has been updated");
            }
            return sb;
        }else{
            String s = browser.getLastUpdate(URL, methodID);
            sb = new StringBuilder(s);
            return sb;
        }
    }

    /**
     * Same as getContents, but without hauling the text from an existing database entry back
     * (only checking that it's there)
     * @return true iff everything is working and new content neede to be downloaded and has been
     * successfully added to the database (in other words, if this URL has been updated!)
     */
    public boolean update(){
        String URL = super.getAddress();
        if(isLostCause()){
            return false;
        }
        if(!browser.beenUpdatedWithin(URL, methodID, interval)){
            StringBuilder sb = super.getContents();
            if(browser.addContent(URL, sb, methodID)){
                return true;
            }
        }
        return false;
    }

}
